package nio.socket.nonblocking;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * 客户端
 */
public class Client {
    /**
     * 客户端1秒钟发送一次请求获取服务器端时间，期间一直保持TCP连接不关闭
     */
    public static void post(String host, int port, long keepalive) {
        SocketChannel socketChannel = null;
        try {
            socketChannel = SocketChannel.open(new InetSocketAddress(host, port));
            ByteBuffer buffer = ByteBuffer.allocate(1024 );
            long endTime = 0;
            do {
                buffer.put("GET CURRENT TIME".getBytes());
                socketChannel.write(buffer);
                buffer.clear();
                //等待服务器响应
                int readCount=socketChannel.read(buffer);
                if (readCount > 0) {
                    System.out.println(Thread.currentThread().getName() + " Get Current Time:" + new String(buffer.array()));
                }
                buffer.clear();
                if (endTime == 0) { // 成功连接后才开始计算存活时间
                    endTime = System.currentTimeMillis() + keepalive;
                }
                Thread.sleep(1000); //在存活期间，每1秒钟获取一次服务器时间
            } while (System.currentTimeMillis() < endTime);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socketChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
